package com.blackcat.demo;

import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;


/**
 * 文件 读取 写入 示例
 * @author zhanghui
 * @创建日期： 2022/11/3 16:48
 */
public class FileDemo {

    // 读取文件
    @Test
    void reader(){
        StringBuilder fileContent = new StringBuilder();
        File file=new File("/Users/blackcat/sinosoft/test.json");
        try {
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(
                        Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(read);
                String line;
                while ((line = reader.readLine()) != null) {
                    fileContent.append(line).append("\n");
                }
                read.close();
                System.out.println(fileContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 读取文件
    @Test
    void reader2(){
        try {
            System.out.println(FileUtils.readLines(new File("/Users/blackcat/sinosoft/test.json"), StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    // 写入文件
    @Test
    void write(){
        try {
            FileUtils.write(new File("/Users/blackcat/sinosoft/test.json"), "123\n456", StandardCharsets.UTF_8, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 写入文件
    @Test
    void write2(){
        String sql = "123\n4567";
        String path = "/Users/blackcat/sinosoft/test.json";
        //将sql输出到本地
        InputStream inputStream=new ByteArrayInputStream(sql.getBytes());
        BufferedInputStream bips = new BufferedInputStream(inputStream);
        PrintWriter out = null;
        try {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(new File(path).toPath()), StandardCharsets.UTF_8)));
            out.write(sql);//写入内容
            //out.append(content);//追加内容
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.close();
            bips.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
